﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace cadbom
{
    class AESUtils
    {
        public static string Encrypt(string content, string key)
        {
            byte[] keyBytes = UTF8Encoding.UTF8.GetBytes(key);

            RijndaelManaged rm = new RijndaelManaged();

            rm.Key = keyBytes;

            rm.Mode = CipherMode.ECB;

            rm.Padding = PaddingMode.PKCS7;

            ICryptoTransform ict = rm.CreateEncryptor();

            byte[] contentBytes = UTF8Encoding.UTF8.GetBytes(content);

            byte[] resultBytes = ict.TransformFinalBlock(contentBytes, 0, contentBytes.Length);

            return ConvertByteToHexString(resultBytes);
        }


        public static string Decrypt(string content, string key)
        {
            byte[] keyBytes = UTF8Encoding.UTF8.GetBytes(key);
            RijndaelManaged rm = new RijndaelManaged();
            rm.Key = keyBytes;
            rm.Mode = CipherMode.ECB;
            rm.Padding = PaddingMode.PKCS7;
            ICryptoTransform ict = rm.CreateDecryptor();
            byte[] contentBytes = ConvertHexStringToBytes(content);
            byte[] resultBytes = ict.TransformFinalBlock(contentBytes, 0, contentBytes.Length);
            return UTF8Encoding.UTF8.GetString(resultBytes);
        }

        public static string ConvertByteToHexString(byte[] bytes)
        {
            StringBuilder ret = new StringBuilder();
            foreach (byte b in bytes)
            {
                //{0:X2} 大写
                ret.AppendFormat("{0:x2}", b);
            }

            var hex = ret.ToString();
            return hex;
        }

        public static byte[] ConvertHexStringToBytes(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
            {
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }
            return returnBytes;
        }
    }
}
